import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class CFromStore with ChangeNotifier {
  Map<String, String> _data = {};
  get data => _data;

  CFromStore({
    Map<String, String> initValue,
  }) {
    _data = initValue ?? {};
    // print(_data);
  }

  void setData(String name, String value) {
    _data[name] = value;
  }

  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  get formKey => _formKey;

  Future submit() async {
    final _form = _formKey.currentState;
    if (_form.validate()) {
      _form.save();
      return _data;
    } else {
      throw "submit validate error";
    }
  }
  @override
  void dispose() {
    super.dispose();
    print(111);
  }
}

typedef CFromWidgetBuilder = Widget Function(BuildContext context);

class CFrom extends StatelessWidget {
  final CFromWidgetBuilder builder;
  final Map<String, String> initValue;
  CFrom({
    @required this.builder,
    this.initValue,
  });
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => CFromStore(initValue: initValue),
        ),
      ],
      child: _CFrom(
        builder: builder,
      ),
    );
  }
}

class _CFrom extends StatelessWidget {
  final CFromWidgetBuilder builder;
  _CFrom({
    @required this.builder,
  });
  @override
  Widget build(BuildContext context) {
    CFromStore store = Provider.of<CFromStore>(context);
    return Form(
      key: store.formKey,
      child: builder(context),
    );
  }
}
